/**
 * Created by LeungZ on 2016/10/16.
 */
import '../form/log.scss';
import logTmp from '../form/log.html';
import logCtrl from '../form/log.ctrl.js';

class Detail {
    constructor(detail, $uiModal, $stateParams, resource, $window, $scope, $timeout, $filter, podSrv) {
        "ngInject";
        this._uiModal = $uiModal;
        this._podSrv = podSrv;
        this._dateFormat = $filter("date");
        this.dbCode = $stateParams.kDbCode;
        this.srvName = $stateParams.srvName;
        this.nodeIp = $stateParams.nodeIp;
        this.rsName = $stateParams.rsName;
        this.name = $stateParams.name;
        this.namesp = $stateParams.namesp;
        this.from = $stateParams.from;
        this._timeout = $timeout;
        this.timer = '';
        var winTimer = '';

        if (detail) {
            this.phase = detail.status.podPhase;
            this.startTime = detail.metadata.creationTimestamp;
            this.podIP = detail.status.podIP;
            this.hostIP = detail.status.nodeName;
            this.labels = this.mapToArray(detail.metadata.labels);
            this.containers = detail.spec.containers;
        }

        if (resource) {
            this.memData = [{
                name: '内存',
                datapoints: []
            }];
            this.memConf = {
                type: 'line',
                color: ['#5093e1'],
                grid: {
                    bottom: "30"
                },
                tooltip: {
                    formatter: '{b} <br/> 内存已占用 <span style="color:#5aa8ff">{c} MB</span>'
                },
                notMerge: true,
                series: [
                    {
                        smooth: true
                    }
                ]
            };

            this.cpuData = [{
                name: 'CPU',
                datapoints: []
            }];
            this.cpuConf = {
                type: 'line',
                color: ['#50c14e'],
                grid: {
                    bottom: "30"
                },
                tooltip: {
                    formatter: '{b} <br/> CPU已占用 <span style="color:#6aff68">{c} 核</span>'
                },
                notMerge: true,
                series: [
                    {
                        smooth: true
                    }
                ]
            };

            this.networkData = {};
            this.netTypes = [{name:"收发流量",type:'bytes'},{name:"收发丢包数",type:'dropped'},{name:"收发错误数",type:'errors'},{name:"收发包数",type:'packets'}];
            angular.forEach(this.netTypes, _type=>{
                this.networkData[_type.type] = [{
                    name: '接收',
                    datapoints: []
                }, {
                    name: '发送',
                    datapoints: []
                }];
            });
            this.networkConf = {
                type: 'line',
                color: ['#2ec7c9', '#b6a2de'],
                grid: {
                    bottom: "30"
                },
                tooltip: {
                    formatter: '{b} <br/> <i style="color:#2ec7c9" class="fa fa-circle"></i> {a0} {c0} 字节' +
                        ' <br/> <i style="color:#b6a2de" class="fa fa-circle"></i> {a1} {c1} 字节'
                },
                notMerge: true,
                series: [{
                    smooth: true
                }]
            };

            if(resource.podMetric){
                this.formatCpuData(resource.podMetric[0]);
                this.formatMemData(resource.podMetric[0]);
                this.formatNetworkData(resource.podMetric[0])
            }
            this.renderChart('cpu');
            if (this.phase == "Running") this.resDataRefresh();
        }

        $window.onresize = ()=> {
            $timeout.cancel(winTimer);
            winTimer = $timeout(()=> {
                this.chartModel().resize();
            }, 50, false);
        };

        $scope.$on('$destroy', ()=> {
            this._timeout.cancel(this.timer);
            $window.onresize = null;
        });
    }

    mapToArray(map) {
        let array = [];
        angular.forEach(Object.keys(map), function (ele) {
            array.push(ele + '=' + map[ele]);
        });
        return array;
    }

    openLogForm() {
        this._uiModal.open({
            animation: true,
            templateUrl: logTmp,
            controller: logCtrl,
            controllerAs: 'vm',
            size: 'lg',
            resolve: {
                containers: ()=> {
                    return this.containers;
                }
            }
        });
    }

    formatCpuData(cpu) {
        let usedCpu = [];
        angular.forEach(cpu.podCpuPerTimes, _cpu=> {
            usedCpu.push({
                x: this._dateFormat(_cpu.timestamp, 'HH:mm:ss'),
                y: (_cpu.usage + 0.005).toFixed(2)
            });
        });
        this.cpuData[0].datapoints = usedCpu;
        this.cpuUsage = (cpu.podCpuUsage + 0.005).toFixed(2);
    }

    formatMemData(mem) {
        let usedMem = [];
        angular.forEach(mem.podMemoryPerTimes, _mem=> {
            usedMem.push({
                x: this._dateFormat(_mem.timestamp, 'HH:mm:ss'),
                y: _mem.usage
            });
        });
        this.memData[0].datapoints = usedMem;
        this.memUsage = mem.podMemoryUsage;
    }

    formatNetworkData(network) {
        let transimit = {};
        let receive = {};
        angular.forEach(this.netTypes, ele=>{
            transimit[ele.type] = [];
            receive[ele.type]   = [];
            angular.forEach(network.podNetworkWhileTime, netPoint => {
                transimit[ele.type].push({
                    x: this._dateFormat(netPoint.timestamp, 'HH:mm:ss'),
                    y: netPoint['tx'+ele.type.replace(ele.type[0],ele.type[0].toUpperCase())]
                });
                receive[ele.type].push({
                    x: this._dateFormat(netPoint.timestamp, 'HH:mm:ss'),
                    y: netPoint['rx'+ele.type.replace(ele.type[0],ele.type[0].toUpperCase())]
                })
            });
            this.networkData[ele.type][0].datapoints = receive[ele.type];
            this.networkData[ele.type][1].datapoints = transimit[ele.type];
        })
    }

    resDataRefresh() {
        this.timer = this._timeout(this.getResData.bind(this), 10000);
    }

    getResData() {
        this._podSrv.getResource({
            names : [{
                name: this.name,
                namespace:  this.namesp,
                nodeName:this.hostIP
            }],
            code: this.dbCode
        }).then(data=> {
            if(data.podMetric){
                this.formatCpuData(data.podMetric[0]);
                this.formatMemData(data.podMetric[0]);
                this.formatNetworkData(data.podMetric[0]);
            }
            this.resDataRefresh();

        }).catch(data=> {
            this._notification.error('获取宿主机资源数据有误.');
        });
    }

    renderChart(type,netType) {
        if (this[type + 'Data'] && this[type + 'Conf'] && type != this.chartType) {
            if (type == 'network') {
                this.chartType = netType;
                this.chartData = this[type + 'Data'][netType] || [{
                    name: '接收',
                    datapoints: []
                }, {
                    name: '发送',
                    datapoints: []
                }];
            } else {
                this.chartType = type;
                this.chartData = this[type + 'Data'];
            }
            this.chartConf = this[type + 'Conf'];
            this.chartConf.tooltip.show = !!this.chartData[0].datapoints.length;
        }
    }
}
export default Detail